﻿using System;
using YJKGridTopologyCal.Index.Quadtree;
using YJKGridTopologyCal.Utilities;

namespace YJKGridTopologyCal.Index.Bintree
{
	public class Root<T> : NodeBase<T>
	{
		public void Insert(Interval itemInterval, T item)
		{
			int subnodeIndex = NodeBase<T>.GetSubnodeIndex(itemInterval, 0.0);
			if (subnodeIndex == -1)
			{
				base.Add(item);
				return;
			}
			Node<T> node = this.Subnode[subnodeIndex];
			if (node == null || !node.Interval.Contains(itemInterval))
			{
				Node<T> node2 = Node<T>.CreateExpanded(node, itemInterval);
				this.Subnode[subnodeIndex] = node2;
			}
			Root<T>.InsertContained(this.Subnode[subnodeIndex], itemInterval, item);
		}

		private static void InsertContained(Node<T> tree, Interval itemInterval, T item)
		{
			Assert.IsTrue(tree.Interval.Contains(itemInterval));
			NodeBase<T> nodeBase;
			if (IntervalSize.IsZeroWidth(itemInterval.Min, itemInterval.Max))
			{
				nodeBase = tree.Find(itemInterval);
			}
			else
			{
				nodeBase = tree.GetNode(itemInterval);
			}
			nodeBase.Add(item);
		}

		protected override bool IsSearchMatch(Interval interval)
		{
			return true;
		}

		private const double Origin = 0.0;
	}
}
